package chu.dejian.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

import chu.dejian.adapter.AttentionAdapter;
import com.sam.blemodule.R;
import chu.dejian.entity.ContactEntity;
import chu.dejian.models.GetAttendersResponse;
import chu.dejian.models.PostAttenderRequestRequest;
import chu.dejian.models.PostAttenderRequestResponse;
import chu.dejian.restApi.RestClient;

import com.sam.ui.base.activity.BaseActivity;
import com.sam.utils.NetUtil;
import com.sam.utils.display.DensityUtils;
import com.sam.utils.L;
import com.sam.utils.T;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;

import chu.dejian.widget.AttentionLevelView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AttentionApplyActivity extends BaseActivity {
	private SwipeMenuListView attenderListView;
	private View contactBookBtn;
	private View darkMask;
	public AttentionLevelView attentionLevelSpinner;
	public EditText attenderNameET,attenderPhoneET;
	private Button addAttentionBtn;
	private AttentionAdapter adapter;
	private List<ContactEntity> contactEntityList;

	private static final int REQUEST_CODE_CHOOSE_CONTACT = 100;
	public static final String EXTRA_KEY_CONTACT_NAME = "name";
	public static final String EXTRA_KEY_CONTACT_PHONE = "phone";
	public static final String EXTRA_KEY_CONTACT_LEVEL = "level";

	@Override
	protected void onCreate(@Nullable Intent savedInstanceStateIntent) {
		setContentView(R.layout.fragment_attention_apply);
	}

	@Override
	protected void findView() {
		contactBookBtn = findViewById(R.id.contact_book_btn);
		attenderListView = (SwipeMenuListView) findViewById(R.id.request_list);
		darkMask = findViewById(R.id.dark_mask);
		attentionLevelSpinner = (AttentionLevelView) findViewById(R.id.attention_level_spinner);
		attenderNameET = (EditText) findViewById(R.id.contact_name);
		attenderPhoneET = (EditText) findViewById(R.id.contact_phone);
		addAttentionBtn = (Button) findViewById(R.id.add_attention);
	}

	@Override
	protected void initView() {
		if(TextUtils.isEmpty(attenderNameET.getText()) || TextUtils.isEmpty(attenderPhoneET.getText()))
			addAttentionBtn.setVisibility(View.GONE);
		contactBookBtn.setOnClickListener(onClickListener);
		darkMask.setOnClickListener(onClickListener);
		attentionLevelSpinner.setSpinnerCallBack(spinnerCallBack);
		addAttentionBtn.setOnClickListener(onClickListener);
		attenderNameET.addTextChangedListener(textWatcher);
		attenderPhoneET.addTextChangedListener(textWatcher);
		contactEntityList = new ArrayList<>();
		adapter = new AttentionAdapter(AttentionApplyActivity.this, R.layout.row_attention_horizontal, contactEntityList,true);
		attenderListView.setMenuCreator(attenderMenuCreator);
		attenderListView.setOnMenuItemClickListener(attenderMenuClickListener);
		attenderListView.setAdapter(adapter);
		restoreIntentData(getIntent());
	}

	SwipeMenuCreator attenderMenuCreator = new SwipeMenuCreator() {
		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem inattentionBtn = new SwipeMenuItem(AttentionApplyActivity.this);
			Drawable inattentionBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			inattentionBtn.setBackground(inattentionBg);
			inattentionBtn.setWidth(DensityUtils.dp2px(AttentionApplyActivity.this, 80));
			inattentionBtn.setTitle(R.string.inattention);
			inattentionBtn.setTitleSize(16);
			inattentionBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(inattentionBtn);
		}
	};

	private SwipeMenuListView.OnMenuItemClickListener attenderMenuClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			final int p = contactEntityList.size()  - 1 - position; // 倒序显示
			switch (index) {
				case 0: //取消关注
					if(!NetUtil.checkNetWork(AttentionApplyActivity.this)) {
						T.showShort(AttentionApplyActivity.this,R.string.operation_denied_network_required);
						return false;
					}
					final int attendId = contactEntityList.get(p).id;
					final int level = AttentionLevelView.ATTENTION_LEVEL.NOTIFY_NOTHING.ordinal();
					RestClient.getAuthedClient().getApiService().deleteAttender(attendId, new Callback() {
						@Override
						public void success(Object o, Response response) {
							L.d("《删除关注人-deleteAttender》", "请求成功");
							if(response.getStatus() == 200) {
								contactEntityList.remove(p);
								adapter.notifyDataSetChanged();
							} else T.showLong(AttentionApplyActivity.this, R.string.cancel_attention_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《删除关注人-deleteAttender》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showLong(AttentionApplyActivity.this, R.string.cancel_attention_failed);
						}
					});
					break;
			}
			return false;
		}
	};

	private AttentionLevelView.SpinnerCallBack spinnerCallBack = new AttentionLevelView.SpinnerCallBack() {
		@Override
		public void onSpinnerOpen() {
			darkMask.setVisibility(View.VISIBLE);
		}

		@Override
		public void onSpinnerClose() {
			darkMask.setVisibility(View.GONE);
		}
	};

	private TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			if(TextUtils.isEmpty(attenderNameET.getText()) || TextUtils.isEmpty(attenderPhoneET.getText())) addAttentionBtn.setVisibility(View.GONE);
			else if(addAttentionBtn.getVisibility() != View.VISIBLE) addAttentionBtn.setVisibility(View.VISIBLE);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode != REQUEST_CODE_CHOOSE_CONTACT || resultCode != RESULT_OK) return;
		restoreIntentData(data);
	}

	private void restoreIntentData(Intent data){
		if(data == null) return;
		attenderNameET.setText(data.getStringExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_NAME));
		attenderPhoneET.setText(data.getStringExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_PHONE));
		attentionLevelSpinner.setLevelByValue(data.getIntExtra(AttentionApplyActivity.EXTRA_KEY_CONTACT_LEVEL, -1));
		if(NetUtil.checkNetWork(this)) asyncAttenders(1);
	}


	private View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int i = v.getId();
			if (i == R.id.contact_book_btn) {
				startActivityForResult(new Intent(AttentionApplyActivity.this,AttentionContactsActivity.class),REQUEST_CODE_CHOOSE_CONTACT);

			} else if (i == R.id.dark_mask) {
				darkMask.setVisibility(View.GONE);

			} else if (i == R.id.add_attention) {
				if(!NetUtil.checkNetWork(AttentionApplyActivity.this)) {
					T.showShort(AttentionApplyActivity.this,R.string.operation_denied_network_required);
					return;
				}
				darkMask.setVisibility(View.GONE);
				final String attenderName = attenderNameET.getText().toString();
				final String attenderPhone = attenderPhoneET.getText().toString();
				if (attentionLevelSpinner.getAttentionLevel() == null) {
					T.showLong(AttentionApplyActivity.this, R.string.choose_attention_level);
					return;
				}
				final int attenderLevelValue = attentionLevelSpinner.getAttentionLevelValue();
				PostAttenderRequestRequest request = new PostAttenderRequestRequest(attenderPhone, attenderLevelValue, attenderName);
				RestClient.getAuthedClient().getApiService().postAttenderRequest(request, new Callback<PostAttenderRequestResponse>() {
					@Override
					public void success(PostAttenderRequestResponse postAttenderRequestResponse, Response response) {
						String requestStr = postAttenderRequestResponse == null ? "null" : postAttenderRequestResponse.toString();
						L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求成功： \n\t返回数据：" + requestStr);// + "\n\t响应数据：" + printResponse(response));
						if (response.getStatus() == 201) {
//								contactEntityList.add(new ContactEntity(postAttenderRequestResponse.getAtrid(),attenderName, attenderPhone, attentionLevelSpinner.getAttentionLevelValue()));
//								adapter.notifyDataSetChanged();
							attenderNameET.setText("");
							attenderPhoneET.setText("");
							T.showLong(AttentionApplyActivity.this, R.string.send_attention_succeed);
						} else T.showLong(AttentionApplyActivity.this, R.string.send_attention_failed);

					}

					@Override
					public void failure(RetrofitError retrofitError) {
						L.d("《用户提交关注请求-postAttenderRequest》" + "\n" + "请求失败： \n\t错误信息：" + retrofitError.toString());
						T.showLong(AttentionApplyActivity.this, R.string.send_attention_failed);
					}
				});

			}
		}
	};



	private boolean isAnsyncAttenders = false;
	private void asyncAttenders(int startPage){
		if(isAnsyncAttenders) return;
		isAnsyncAttenders = true;
		RestClient.getAuthedClient().getApiService().getAttenders(startPage,new Callback<GetAttendersResponse>() {
			@Override
			public void success(GetAttendersResponse getAttendersResponse, Response response) {
				L.d("《获取关注我的用户列表-getAttendees》\n请求成功： \n\t返回数据：" + getAttendersResponse.toString());
				final List<GetAttendersResponse.ResultsEntity> attendees = getAttendersResponse.getResults();
				if(attendees == null || attendees.size() == 0) return;
				for(GetAttendersResponse.ResultsEntity attendee : attendees){
					ContactEntity contactEntity = new ContactEntity(attendee.getAtid(),attendee.getName(),attendee.getAttender_name(),attendee.getAttendee_level());
					if(!contactEntityList.contains(contactEntity)){
						contactEntityList.add(contactEntity);
					}
				}
				isAnsyncAttenders = false;
				if(getAttendersResponse.getNext() != null && !getAttendersResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getAttendersResponse.getNext()).getQueryParameter("page"));
					asyncAttenders(nextPage);
				} else runOnUiThread(new Runnable() {
					@Override
					public void run() {
						adapter.notifyDataSetChanged();
					}
				});
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取关注我的用户列表-getAttendees》\n请求失败： \n\t错误信息：" + retrofitError.toString());
			}
		});
	}
}
